package org.sqp.conn.impl;

import okhttp3.Cookie;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.sqp.conn.Browser;
import org.sqp.conn.UserAgent;

import java.io.IOException;

public class ChromeBrowser implements Browser {
    private OkHttpClient okHttpClient;
    private SimpleCookieJar cookieJar =  new SimpleCookieJar();

    public ChromeBrowser(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    public ChromeBrowser() {
        this.okHttpClient = new OkHttpClient.Builder().cookieJar(cookieJar).build();
    }

    public void addCookie(String name, String value, String domain, String path) {
        Cookie cookie = new Cookie.Builder().name(name).value(value).domain(domain).path(path).build();
        cookieJar.add(cookie);
    }

    public Response request(Request request) {
        try {
            return okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Request.Builder getRequestBuilder() {
        return new Request.Builder()
                .addHeader("User-Agent", UserAgent.chrome)
                .addHeader("Cache-Control", "max-age=0")
                .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7");
    }
}
